package com.csst.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.json.JSONObject;
import org.springframework.stereotype.Controller;

import com.csst.bean.Account;
import com.csst.bean.User;
import com.csst.service.AccountService;
import com.csst.util.HttpUtil;
import com.csst.util.SignatureTool;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Controller
public class ReChargeAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private String money;
	private String password;
	@Resource
	private AccountService service;

	public String getMoney() {
		return money;
	}

	public void setMoney(String money) {
		this.money = money;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> session = ActionContext.getContext().getSession();
		User user = (User) session.get("user");

		Map<String, String> map = new HashMap<String, String>();
		map.put("merID", "123456");
		map.put("fromBankCardNum", user.getUserbank().getCardId());
		map.put("toBankCardNum", "6225123498760000123");
		double m = Double.parseDouble(money);
		long mm = (long) (m * 100);
		String mstr = String.valueOf(mm);
		map.put("amount", mstr);
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String orderDate = sdf.format(date);
		map.put("orderDate", orderDate);
		SignatureTool tool = new SignatureTool();
		tool.setTransferParameter(123456, user.getUserbank().getCardId(),
				"6225123498760000123", mm, orderDate, password,
				"jksas-jklwj-lwjjh-wmkhs-jklkj");
		String merSignMsg = tool.signature();
		map.put("merSignMsg", merSignMsg);
		String result = HttpUtil.doPost(
				"http://bank:8080/obs/merchant/transfer", map);
		JSONObject job = new JSONObject(result);
		session.put("message",job.get("result"));
		if (job.get("result").equals("SC")) {
			Account account=user.getAccount();
			account.setMoney(user.getAccount().getMoney()+m);
			service.updateAccount(account);
			return SUCCESS;
		}else if (job.get("result").equals("AI")) {
			return "fail";
		}else if (job.get("result").equals("TI")) {
			return "bankcardlock";
		}else if (job.get("result").equals("IC")) {
			return "fail";
		}
		else {
			return "other";
		}
	}

}
